package codeRandomThoughts.Test226翻转二叉树;

import codeRandomThoughts.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 迭代法用层序遍历也可,只要对遍历的每个节点反转左右子树就行
 */
public class Solution2 {
    public TreeNode invertTree(TreeNode root) {
        if (root==null){
            return root;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode node = root;
        queue.offer(node);

        while (!queue.isEmpty()) {
            int size = queue.size();

            while (size-- > 0) {
                node = queue.poll();
                //翻转此节点的左右子树
                TreeNode tem = node.left;
                node.left = node.right;
                node.right = tem;

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }
}
